package com.apexedu.sync.node.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apexedu.biz.Const;
import com.apexedu.biz.entity.TSysUserInfo;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.framework.util.SysPropertiesUtil;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.entity.TSysDepart;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.sync.contant.Constants;
import com.apexedu.sync.engine.ISyncContext;
import com.apexedu.sync.entity.SyncAppModelMsg;
import com.apexedu.sync.exception.AuCSyncException;
import com.apexedu.sync.node.ISyncNode;
import com.apexedu.sys.SysConstant;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.crypto.LiveBosMD5;

/**
 * 同步livebos系统用户
 * Created by ly on 2015/1/12.
 */
public class LivebosUserNode extends BaseNode implements ISyncNode {

	@Override
	public void execute(ISyncContext context) throws AuCSyncException {
		DBMUtil dbmUtil = context.getDbmUtil();//多数据源工具类
		BaseDao baseDao = context.getBaseDao();
		String msg;
		try {
			//String dbType = context.getDbmUtil().getDbType(); //数据库类型
			String dbType = dbmUtil.getDbType(); //数据库类型
			String sql_needAddUserList = "";
			if (Const.DbType.ORACLE.equals(dbType)) { //oracle
				sql_needAddUserList += " select t.name as username,t.userid as userloginid,";
				sql_needAddUserList += " t.status as state,t.yhlx as usertype,nvl(t.ls,'000000') as userpwd,";
				sql_needAddUserList += " case when yhlx = 1 then 'teacher' else 'student' end as orname,t.yhlx as yhlx ";
				sql_needAddUserList += " from tuser t ";
				sql_needAddUserList += " left join lborganization a on a.id=t.orgid";
				sql_needAddUserList += " where 1=1";
				sql_needAddUserList += " and (t.state!='0' or t.state is null) ";
				//sql_needAddUserList += " and t.ls is not null ";
				sql_needAddUserList += " and t.yhlx is not null";
			} else if (Const.DbType.SQLSERVER.equals(dbType)) { //sqlserver
				sql_needAddUserList += " select t.name as username,t.userid as userloginid,";
				sql_needAddUserList += " t.status as state,t.yhlx as usertype,isnull(t.ls,'000000') as userpwd,";
				sql_needAddUserList += " case when yhlx = 1 then 'teacher' else 'student' end as orname,t.yhlx as yhlx ";
				sql_needAddUserList += " from tuser t ";
				sql_needAddUserList += " left join lborganization a on a.id=t.orgid";
				sql_needAddUserList += " where t.state!='0' or t.state='' and t.yhlx!='' ";
			}
			List<TSysUser> needAddUserList = dbmUtil.queryAllBeanList(sql_needAddUserList, TSysUser.class); //新增集合

			//系统中已经禁用的用户
			String sql_userMap_disable = "select * from t_sys_user where state = 0";
			List<TSysUser> oldDisabledUserList = DBUtil.queryAllBeanList(sql_userMap_disable, TSysUser.class);

			//用户其他信息
			List<TSysUserInfo> listInfo = new ArrayList<TSysUserInfo>();
			//本次增量更新的用户map
			Map<String, TSysUser> userAddedMap = new HashMap<String, TSysUser>();
			//校验是否存在，已存在的不需要同步
			for (int i = 0; i < needAddUserList.size(); i++) {
				TSysUser needAddUserTemp = needAddUserList.get(i);
				String userIdTemp = needAddUserTemp.getUserloginid();
				TSysUser cachedUser = context.getMapUser().get(userIdTemp);
				if (null != cachedUser) { //系统缓存用户map中已存在该用户，说明门户中存在该用户，排除该用户
					needAddUserList.remove(i);
					i--;
					continue;
				} else {//系统缓存用户map中不存在该用户，说明这可能是一个新增用户，也可能是一个禁用后重新启用的用户 
					/* 检测该用户是否为禁用的用户，如果是，则直接启用，否则新增 */
					Boolean isUserExistsAndDisabled = false;
					TSysUser existsAndDisabledUser = null;
					for (int j = 0; j < oldDisabledUserList.size(); j++) {
						TSysUser oldDisabledUserTemp = oldDisabledUserList.get(j);
						if (userIdTemp.equals(oldDisabledUserTemp.getUserloginid())) {
							existsAndDisabledUser = oldDisabledUserTemp;
							isUserExistsAndDisabled = true;
							break;
						}
					}

					String wid = null;
					if (isUserExistsAndDisabled) {//该用户在门户中已存在，但被禁用了
						wid = existsAndDisabledUser.getUserid();
						needAddUserTemp.setUserid(wid);
					} else {//该用户在门户中不存在
						wid = SeqFactory.getNewSequenceAlone();
						needAddUserTemp.setUserid(wid);//主键
						needAddUserTemp.setDepart(new TSysDepart("000"));
					}
					if (Const.DbType.ORACLE.equals(dbType)) { //oracle数据库的方案，交院用
						if (StringUtil.isNotBlank(needAddUserTemp.getUserpwd())) {
							needAddUserTemp.setUserpwd(LiveBosMD5.getMD5Digest(needAddUserTemp.getUserpwd()).toUpperCase());
						} else { //没有设置密码的保存默认密码
							needAddUserTemp.setUserpwd(LiveBosMD5.getMD5Digest(SysPropertiesUtil.get(IdConstants.INITIAL_PASSWORD)).toUpperCase());
						}
					} else if (Const.DbType.SQLSERVER.equals(dbType)) { //sqlserver
						if (StringUtil.isNotBlank(needAddUserTemp.getUserpwd())) {
							needAddUserTemp.setUserpwd(LiveBosMD5.getMD5Digest(needAddUserTemp.getUserpwd()).toUpperCase());
						} else { //没有设置密码的保存默认密码
							needAddUserTemp.setUserpwd(LiveBosMD5.getMD5Digest(SysPropertiesUtil.get(IdConstants.INITIAL_PASSWORD)).toUpperCase());
						}
					}

					//保存到用户集合中，用于用户的校验和用户角色的校验
					userAddedMap.put(userIdTemp, needAddUserTemp);
					//保存到用户信息附加表中，用于用户关联门户站点
					if (StringUtil.isNotBlank(needAddUserTemp.getYhlx())) {
						TSysUserInfo newSysUserInfo = new TSysUserInfo(wid, Integer.parseInt(needAddUserTemp.getYhlx()));
						listInfo.add(newSysUserInfo);
					}
				}
			}

			if (!needAddUserList.isEmpty()) {
				if ("true".equals(SysPropertiesUtil.get(IdConstants.HAS_LDAP))) { //有ldap的同步到ldap中
					//                    System.out.print("1");
					//                    LdapUtil.createO(); //创建组织机构
					//                    sql = "select id as departid,name as departname,OrgCode as departcode from lborganization";
					//                    List<TSysDepart> departList = dbmUtil.queryAllBeanList(sql, TSysDepart.class);
					//                    LdapUtil.createOuTempAll(departList); //创建组件单元
					//批量添加到ldap中
					//                    List<TSysUser> listAddLdap = new ArrayList<TSysUser>();
					//                    for (TSysUser user : listAdd) {
					//                        if (StringUtil.isNotBlank(user.getOrname()) && !"_".equals(user.getOrname()))
					//                            for (TSysDepart depart : departList) {
					//                                if (user.getOrname().equals(depart.getDepartname() + "_" + depart.getDepartcode())) {
					//                                    listAddLdap.add(user);
					//                                }
					//                            }
					//                    }
					//                    LdapUtil.addUserTempAll(listAdd);

				}

				//				System.out.println("==================筛选后的第二次");
				//				for (TSysUser needAddUser : needAddUserList) {
				//					if (needAddUser.getUserid().equals("tiantingyi")) {
				//						System.out.println("=============" + needAddUser.getUserid());
				//					}
				//				}

				//保存新增集合
				//baseDao.saveAll(needAddUserList); 
				baseDao.saveOrUpdateAll(needAddUserList);
				//将本次新增的用户更新到系统缓存用户中
				context.getMapUser().putAll(userAddedMap);
				//插入用户信息表 用户类型等信息
				baseDao.saveOrUpdateAll(listInfo);
			}
			msg = "插入：" + needAddUserList.size() + "条。";
			BusinessLogUtil.log(getUserInfo(context), SysConstant.CZDX_T_SYS_USER, Const.LOG_ACTION_UPDATE, "", msg);
			context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.USER, msg));
			//dbmUtil.executeSQL("update tuser set state='0' where ls is not null and yhlx is not null");//标记状态为已同步
			dbmUtil.executeSQL("update tuser set state='0' where (state is null or state != '0') and yhlx is not null");//标记状态为已同步
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getMessage().contains("ORA-00904")) {
				msg = e.getMessage().substring(e.getMessage().indexOf("ORA-00904") + 9);
				msg = msg.substring(msg.indexOf(".") + 2);
				msg = msg.substring(0, msg.indexOf("\""));
				msg = "tuser表/视图缺" + msg + "字段";
				log.error("LivebosUserNode error : " + e);
				context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.USER, msg));
				throw new AuCSyncException(AuCSyncException.TABLE_VIEW_COLUMN_NO_FOUND, msg);
			}
			msg = e.getMessage();
			log.error("LivebosUserNode error : " + e);
			context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.USER, msg));
			throw new AuCSyncException(AuCSyncException.UNKNOWN_SERVICE_ERROR, msg);
		}
	}
}
